package cn.wolfcode.luowowo.controller;

import cn.wolfcode.luowowo.domain.Travel;
import cn.wolfcode.luowowo.query.TravelQuery;
import cn.wolfcode.luowowo.service.ITravelService;
import cn.wolfcode.luowowo.util.JsonResult;
import cn.wolfcode.luowowo.util.UMEditorUploader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 游记控制器
 */
@Controller
@RequestMapping("/travel")
public class TravelController {
    //注入游记服务接口
    @Autowired
    private ITravelService travelService;

    //查询
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") TravelQuery qo) {
        Page<Travel> page = travelService.query(qo);
        model.addAttribute("page", page);
        return "travel/list";
    }

    //根据id获取文本内容
    @RequestMapping("/getContentById")
    @ResponseBody
    public Object getContentById(String id) {
        Travel travel = travelService.get(id);
        return JsonResult.success(travel.getContent());
    }

    //上传图片
    @RequestMapping("/contentImage")
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }

    //发布/拒绝
    @RequestMapping("/changeState")
    @ResponseBody
    public Object changeState(String id,int state) {
        travelService.changeState(id,state);
        return JsonResult.success();
    }
}
